"""深度研究规划节点"""

from typing import Dict, List, Any, Optional
from core.graph.chat_graph import ChatState, ResearchContext, ResearchStage


class DeepResearchPlanner:
    """深度研究规划器"""
    
    def __init__(self):
        self.research_templates = {
            "concept_analysis": {
                "stages": [
                    ResearchStage.ANALYSIS,
                    ResearchStage.HYPOTHESIS,
                    ResearchStage.VERIFICATION,
                    ResearchStage.CONCLUSION
                ],
                "questions": [
                    "这个概念的核心定义是什么？",
                    "它在 Cairo/Starknet 生态中的作用是什么？",
                    "与其他相关概念的关系如何？",
                    "实际应用场景有哪些？",
                    "有什么限制或注意事项？"
                ]
            },
            "code_deep_dive": {
                "stages": [
                    ResearchStage.ANALYSIS,
                    ResearchStage.HYPOTHESIS,
                    ResearchStage.VERIFICATION,
                    ResearchStage.SYNTHESIS,
                    ResearchStage.CONCLUSION
                ],
                "questions": [
                    "代码的整体架构是什么？",
                    "关键算法和数据结构是什么？",
                    "性能特征如何？",
                    "可能的优化点在哪里？",
                    "安全性考虑有哪些？",
                    "与最佳实践的对比如何？"
                ]
            },
            "problem_solving": {
                "stages": [
                    ResearchStage.ANALYSIS,
                    ResearchStage.HYPOTHESIS,
                    ResearchStage.VERIFICATION,
                    ResearchStage.SYNTHESIS,
                    ResearchStage.CONCLUSION
                ],
                "questions": [
                    "问题的根本原因是什么？",
                    "有哪些可能的解决方案？",
                    "每种方案的优缺点是什么？",
                    "推荐的解决方案是什么？",
                    "如何验证解决方案的有效性？"
                ]
            },
            "comparison_study": {
                "stages": [
                    ResearchStage.ANALYSIS,
                    ResearchStage.HYPOTHESIS,
                    ResearchStage.VERIFICATION,
                    ResearchStage.SYNTHESIS,
                    ResearchStage.CONCLUSION
                ],
                "questions": [
                    "比较对象的基本特征是什么？",
                    "主要差异点在哪里？",
                    "各自的优势和劣势是什么？",
                    "适用场景有何不同？",
                    "如何选择最适合的方案？"
                ]
            }
        }

    def determine_research_type(self, query: str, code_context: Dict[str, Any]) -> str:
        """确定研究类型"""
        query_lower = query.lower()
        
        # 比较研究
        if any(word in query_lower for word in ["比较", "对比", "区别", "差异", "vs", "versus", "compare"]):
            return "comparison_study"
        
        # 问题解决
        if any(word in query_lower for word in ["问题", "错误", "解决", "修复", "bug", "issue", "problem"]):
            return "problem_solving"
        
        # 代码深度分析
        if code_context.get("has_code") and any(word in query_lower for word in ["分析", "解释", "原理", "机制"]):
            return "code_deep_dive"
        
        # 概念分析（默认）
        return "concept_analysis"

    def generate_research_questions(self, research_type: str, query: str, 
                                  code_context: Dict[str, Any]) -> List[str]:
        """生成研究问题"""
        template = self.research_templates.get(research_type, self.research_templates["concept_analysis"])
        base_questions = template["questions"].copy()
        
        # 根据具体查询定制问题
        customized_questions = []
        
        for question in base_questions:
            # 替换通用词汇为具体内容
            customized = question
            if "这个概念" in question and any(word in query for word in ["什么是", "定义"]):
                # 提取概念名称
                concept_match = None
                for word in query.split():
                    if word not in ["什么是", "的", "？", "?"]:
                        concept_match = word
                        break
                if concept_match:
                    customized = question.replace("这个概念", concept_match)
            
            customized_questions.append(customized)
        
        # 添加特定于代码的问题
        if code_context.get("has_code"):
            code_type = code_context.get("code_type", "")
            if code_type == "contract":
                customized_questions.append("这个合约的安全性如何？")
                customized_questions.append("合约的 gas 效率如何？")
            elif code_type == "function":
                customized_questions.append("函数的时间复杂度是多少？")
                customized_questions.append("是否有潜在的边界情况？")
        
        return customized_questions

    def create_initial_hypotheses(self, questions: List[str], query: str) -> List[Dict[str, Any]]:
        """创建初始假设"""
        hypotheses = []
        
        for i, question in enumerate(questions[:3]):  # 限制前3个问题
            hypothesis = {
                "id": f"hypothesis_{i}",
                "question": question,
                "hypothesis": f"基于问题 '{question}' 的初步假设需要通过分析确定",
                "confidence": 0.3,  # 初始置信度较低
                "evidence": [],
                "status": "pending"
            }
            hypotheses.append(hypothesis)
        
        return hypotheses

    def plan_research_stages(self, research_type: str) -> List[ResearchStage]:
        """规划研究阶段"""
        template = self.research_templates.get(research_type, self.research_templates["concept_analysis"])
        return template["stages"]


# 全局研究规划器实例
research_planner = DeepResearchPlanner()


def plan_research(state: ChatState) -> ChatState:
    """研究规划节点"""
    user_text = state["messages"][-1]["content"] if state["messages"] else ""
    cairo_context = state.get("cairo_context", {})
    
    # 确定研究类型
    research_type = research_planner.determine_research_type(user_text, cairo_context)
    
    # 生成研究问题
    research_questions = research_planner.generate_research_questions(research_type, user_text, cairo_context)
    
    # 创建初始假设
    hypotheses = research_planner.create_initial_hypotheses(research_questions, user_text)
    
    # 规划研究阶段
    stages = research_planner.plan_research_stages(research_type)
    
    # 创建研究上下文
    research_context = ResearchContext(
        current_stage=ResearchStage.INITIAL,
        research_questions=research_questions,
        hypotheses=hypotheses,
        evidence=[],
        intermediate_results=[],
        final_report=None
    )
    
    # 更新状态
    state["research_context"] = research_context
    state["research_depth"] = 3  # 深度研究模式
    state["max_loops"] = 5  # 最大循环次数
    state["loop_count"] = 0
    
    # 设置下一步动作
    state["next_action"] = "research_execution"
    
    return state


def execute_research_stage(state: ChatState) -> ChatState:
    """执行研究阶段（修复版）"""
    research_context = state.get("research_context")
    if not research_context:
        state["next_action"] = "answer_generation"
        return state
    
    current_stage = research_context["current_stage"]
    loop_count = state.get("loop_count", 0)
    max_loops = state.get("max_loops", 2)  # 减少最大循环次数
    
    # 检查是否达到最大循环次数
    if loop_count >= max_loops:
        research_context["current_stage"] = ResearchStage.CONCLUSION
        state["next_action"] = "answer_generation"  # 直接生成答案
        return state
    
    # 简化阶段推进逻辑，避免外部依赖
    if current_stage == ResearchStage.INITIAL:
        # 开始分析阶段，直接使用已有的知识
        research_context["current_stage"] = ResearchStage.ANALYSIS
        
        # 创建分析结果
        user_text = state["messages"][-1]["content"] if state["messages"] else ""
        analysis_result = {
            "type": "analysis",
            "content": f"深度分析用户问题: {user_text}",
            "stage": "analysis",
            "importance": 0.8
        }
        research_context["intermediate_results"].append(analysis_result)
        
        # 直接进入下一阶段，不依赖外部知识检索
        state["next_action"] = "research_execution"
        
    elif current_stage == ResearchStage.ANALYSIS:
        # 分析完成，直接进入综合阶段，跳过假设和验证
        research_context["current_stage"] = ResearchStage.SYNTHESIS
        
        # 创建假设结果
        hypothesis_result = {
            "type": "hypothesis",
            "content": "基于分析生成的关键假设",
            "stage": "hypothesis",
            "importance": 0.7
        }
        research_context["intermediate_results"].append(hypothesis_result)
        
        state["next_action"] = "research_synthesis"
        
    elif current_stage == ResearchStage.SYNTHESIS:
        # 综合完成，进入结论阶段
        research_context["current_stage"] = ResearchStage.CONCLUSION
        state["next_action"] = "answer_generation"
    
    else:
        # 其他情况直接生成答案
        state["next_action"] = "answer_generation"
    
    # 增加循环计数
    state["loop_count"] = loop_count + 1
    
    return state


def synthesize_research(state: ChatState) -> ChatState:
    """综合研究结果（修复版）"""
    research_context = state.get("research_context")
    if not research_context:
        state["next_action"] = "answer_generation"
        return state
    
    # 收集所有证据和中间结果
    evidence = research_context.get("evidence", [])
    intermediate_results = research_context.get("intermediate_results", [])
    hypotheses = research_context.get("hypotheses", [])
    
    # 生成综合报告
    synthesis_result = {
        "type": "synthesis",
        "summary": "基于深度研究的综合分析结果",
        "key_findings": [],
        "validated_hypotheses": [],
        "remaining_questions": [],
        "confidence_level": 0.8
    }
    
    # 分析假设验证情况
    for hypothesis in hypotheses:
        if hypothesis.get("status") == "validated":
            synthesis_result["validated_hypotheses"].append(hypothesis)
        elif hypothesis.get("status") == "pending":
            synthesis_result["remaining_questions"].append(hypothesis["question"])
    
    # 提取关键发现
    for result in intermediate_results:
        if result.get("importance", 0) > 0.5:  # 降低阈值
            synthesis_result["key_findings"].append(result.get("content", ""))
    
    # 如果没有足够的发现，添加默认内容
    if not synthesis_result["key_findings"]:
        user_text = state["messages"][-1]["content"] if state["messages"] else ""
        synthesis_result["key_findings"].append(f"针对问题 '{user_text}' 的深度分析已完成")
    
    # 计算整体置信度
    if hypotheses:
        total_confidence = sum(h.get("confidence", 0) for h in hypotheses)
        synthesis_result["confidence_level"] = total_confidence / len(hypotheses)
    
    # 添加到中间结果
    research_context["intermediate_results"].append(synthesis_result)
    
    # 直接生成答案，不再进入结论阶段
    state["next_action"] = "answer_generation"
    
    return state


def conclude_research(state: ChatState) -> ChatState:
    """得出研究结论"""
    research_context = state.get("research_context")
    if not research_context:
        state["next_action"] = "answer_generation"
        return state
    
    # 生成最终报告
    intermediate_results = research_context.get("intermediate_results", [])
    research_questions = research_context.get("research_questions", [])
    
    final_report = {
        "title": "深度研究报告",
        "executive_summary": "基于多阶段分析的深度研究结果",
        "methodology": "采用了分析-假设-验证-综合的研究方法",
        "key_findings": [],
        "conclusions": [],
        "recommendations": [],
        "limitations": [],
        "confidence_score": 0.0
    }
    
    # 提取关键发现和结论
    for result in intermediate_results:
        if result.get("type") == "synthesis":
            final_report["key_findings"].extend(result.get("key_findings", []))
            final_report["confidence_score"] = result.get("confidence_level", 0.0)
    
    # 生成结论
    if final_report["key_findings"]:
        final_report["conclusions"] = [
            "通过多阶段分析，我们获得了以下深入理解：",
            *final_report["key_findings"][:3]  # 取前3个关键发现
        ]
    
    # 生成建议
    final_report["recommendations"] = [
        "建议进一步验证关键假设",
        "考虑实际应用场景中的限制因素",
        "持续关注相关技术发展"
    ]
    
    # 说明限制
    final_report["limitations"] = [
        "分析基于当前可用信息",
        "某些假设可能需要实际验证",
        "技术发展可能影响结论的时效性"
    ]
    
    # 设置最终报告
    research_context["final_report"] = final_report
    
    # 设置下一步动作
    state["next_action"] = "answer_generation"
    
    return state